import { createRouter, createWebHistory } from 'vue-router';
import PageRouter from './page/';
import ViewsRouter from './views/';
import ItemDetailRouter from './project-view-detail';
import AvueRouter from './avue-router';
import i18n from '@/lang';
import Store from '@/store/';
// 创建路由
const Router = createRouter({
  base: import.meta.env.VITE_APP_BASE,
  history: createWebHistory(),
  routes: [...PageRouter, ...ViewsRouter, ...ItemDetailRouter],
});
AvueRouter.install({
  store: Store,
  router: Router,
  i18n,
});

Router.$avueRouter.formatRoutes(Store.getters.menuAll, true);

export function resetRouter() {
  // 重置路由 比如用于身份验证失败，需要重新登录时 先清空当前的路有权限
  const newRouter = createRouter();
  Router.matcher = newRouter.matcher; // reset router
  // eslint-disable-next-line no-undef
  AvueRouter.install(Vue, {
    router: Router,
    store: Store,
    i18n,
  });
}

Router.beforeEach((to, from, next) => {
  // 记录跳转工作台的上一个路由
  if (to.path === '/project-control/project-work/workbench-homepage'
  && !from.path.includes('project-control/project-work')) {
    const store = useStore();
    store.commit('SET_BEFORE_ROUTE', from.path);
  }

  next();
});

export default Router;
